package top.jiangqiang.qianyi.common.jackson;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.extra.spring.SpringUtil;
import top.jiangqiang.qianyi.common.constants.http.Error500Status;
import top.jiangqiang.qianyi.common.crypto.EncryptService;
import top.jiangqiang.qianyi.common.exception.Error500Exception;

/**
 * 序列化时加密，由于接口响应的数据都是json数据，最终都会调用jackson进行序列化，所以此类可以作为通用的加密方式
 */
@Slf4j
public class EncryptionSerializer extends StdSerializer<String> {

    public EncryptionSerializer() {
        super(String.class);
    }

    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) {
        try {
            String encryptedValue = SpringUtil.getBean(EncryptService.class).httpEncrypt(value);
            gen.writeString(encryptedValue);
        } catch (Exception var5) {
            log.error("EncryptionSerializer failed， decryptionValue:{}", value);
            throw new Error500Exception(Error500Status.INTERNAL_SERVER_ERROR, var5);
        }
    }
}